<template>
  <div>
    <h4>{{msg}}</h4>

    <a href="javascript:void(0)" @click="showAddForm">添加</a>
    <table width="100%" border="1">
      <tr>
        <td>id</td>
        <td>name</td>
        <td>score</td>
        <td>操作</td>
      </tr>
      <tr v-for="(stu,idx) in stus" :key="stu.id">
        <td>{{stu.id}}</td>
        <td>{{stu.name}}</td>
        <td>{{stu.score}}</td>
        <td>
          <a href="javascript:void(0)" @click="modifyOne(stu.id)">修改</a>
          <a href="javascript:void(0)" @click="removeStu(stu.id)">删除</a>
        </td>
      </tr>
    </table>


    <form action="" v-show="showForm">
      <input type="hidden" v-model="stu.id"><br/>
      name:<input type="text" v-model="stu.name"><br/>
      score:<input type="text" v-model="stu.score"><br/>
      <input type="button" value="保存" @click="saveStu">
    </form>
  </div>
</template>

<script>


import instance from "../../utils/request";

export default {
  name: "index",
  data(){
    return {
      msg:"学生管理",
      stus:[],
      stu:{},
      showForm:false
    }
  },
  created() {
    // 调用函数，查所有
    this.queryAllStu();
  },
  methods:{
    queryAllStu(){
      // 发异常请求，查所有
      instance.get("/stu/queryAll")
        .then(res => this.stus=res.data);

    },
    modifyOne(id){
      this.showForm = true;
      instance.get("/stu/modifyOne?id="+id)
        .then(res => this.stu = res.data);
    },
    saveStu(){ // 添加和修改的保存
      if (this.stu.id){// 修改
        instance.post("/stu/modify", this.stu)
          .then(res => {
            this.stu = {};
            this.showForm = false;
            this.queryAllStu();
          });
      } else {
        instance.post("/stu/add", this.stu)
          .then(res => {
            this.stu = {};
            this.showForm = false;
            this.queryAllStu();
          });
      }
    },
    removeStu(id){
      this.showForm = false;
      if (window.confirm("确认删除吗？")) {
        instance.get("/stu/remove?id=" + id)
          .then(res => this.queryAllStu());
      }
    },
    showAddForm(){
      this.stu = {};
      this.showForm = true;
    }
  }
}
</script>

<style scoped>

</style>
